package com.wedo.mall.fragment;

import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.util.ArrayMap;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.listener.OnItemClickListener;
import com.e.library.fragment.EFragment;
import com.e.library.http.EApi;
import com.e.library.http.EClient;
import com.e.library.http.EObserver;
import com.e.library.http.EResponse;
import com.e.library.utils.EUtils;
import com.e.library.utils.EViewUtils;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.hyphenate.easeui.map.GLocation;
import com.wedo.mall.BuildConfig;
import com.wedo.mall.R;
import com.wedo.mall.WApp;
import com.wedo.mall.activity.MapActivity;
import com.wedo.mall.activity.agent.AgentDetailActivity;
import com.wedo.mall.activity.agent.AgentIntroActivity;
import com.wedo.mall.activity.agent.AgentsActivity;
import com.wedo.mall.activity.chat.ConsultActivity;
import com.wedo.mall.activity.goods.GoodsActivity;
import com.wedo.mall.activity.goods.GoodsDetailActivity;
import com.wedo.mall.activity.main.BannerActivity;
import com.wedo.mall.activity.MainActivity;
import com.wedo.mall.activity.main.NearbyActivity;
import com.wedo.mall.activity.main.ScannerActivity;
import com.wedo.mall.activity.main.SearchActivity;
import com.wedo.mall.activity.main.WebActivity;
import com.wedo.mall.activity.register.AgentInfoActivity;
import com.wedo.mall.adapter.GoodsAdapter;
import com.wedo.mall.adapter.GoodsCategoryAdapter;
import com.wedo.mall.adapter.FavourableAdapter;
import com.wedo.mall.adapter.AgentAdapter;
import com.wedo.mall.adapter.SimilarAdapter;
import com.wedo.mall.entity.Banner;
import com.wedo.mall.entity.Goods;
import com.wedo.mall.entity.GoodsCategory;
import com.wedo.mall.entity.Agent;
import com.wedo.mall.util.WUtils;
import com.wedo.mall.widget.BannerHolder;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindString;
import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;

/**
 * Created by lxy on 2017/6/8.
 */

public class MainFragment extends EFragment<MainActivity> implements OnMapReadyCallback,GoogleMap.OnMapClickListener,GoogleMap.OnMarkerClickListener{

    @BindString(R.string.category_more) String category_more;
    @BindView(R.id.cb_banner) ConvenientBanner cb_banner;
    @BindView(R.id.rv_category) RecyclerView rv_category;
    @BindView(R.id.rv_recommend) RecyclerView rv_recommend;
    @BindView(R.id.rv_shop) RecyclerView rv_shop;
    @BindView(R.id.rv_favourable) RecyclerView rv_favourable;
    @BindView(R.id.mv_map) MapView mv_map;
    private GoogleMap mMap;

    private List<Banner> banners;
    private GoodsCategoryAdapter mGoodsCategoryAdapter;
    private SimilarAdapter mRecommendAdapter;
    private AgentAdapter mAgentAdapter;
    private FavourableAdapter mFavourableAdapter;

    public static MainFragment with(){
        return new MainFragment();
    }
    @Override
    protected int layout() {
        return R.layout.fragment_main;
    }

    @Override
    protected void onFragmentCreated(View contentView, final Bundle savedInstanceState) {

        rv_shop.setHasFixedSize(true);
        EViewUtils.horizontal(rv_shop);
        rv_shop.setAdapter(mAgentAdapter = AgentAdapter.main(getContext(),new ArrayList<Agent>()));
        mAgentAdapter.listener(activity());

        map(savedInstanceState);

        banners();
        cb_banner.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                Banner banner = banners.get(position);

                if (banner.url()){
                    Bundle extras = new Bundle();
                    if(TextUtils.isEmpty(banner.url)) {
                        extras.putString(WebActivity.EXTRA_URL,banner.image);
                    }else {
                        extras.putString(WebActivity.EXTRA_URL,banner.url);
                    }
                    activity().toActivity(WebActivity.class,extras);
                }else if (banner.goods()){
                    GoodsDetailActivity.toDetail(activity(),banner.content);
                }else if (banner.shop()){
                    AgentDetailActivity.toDetail(activity(),banner.content);
                }else if (banner.detail()){
                    Bundle extras = new Bundle();
                    extras.putParcelable("banner",banner);
                    activity().toActivity(BannerActivity.class,extras);
                }

            }
        });
        BannerHolder.align(cb_banner);

        rv_category.setHasFixedSize(true);
        rv_category.setNestedScrollingEnabled(false);
        rv_category.setLayoutManager(new GridLayoutManager(getContext(),4));
        mGoodsCategoryAdapter = new GoodsCategoryAdapter(getContext(),new ArrayList<GoodsCategory>());
        rv_category.setAdapter(mGoodsCategoryAdapter);
        mGoodsCategoryAdapter.listener(activity());
        categories();

        rv_recommend.setHasFixedSize(true);
        EViewUtils.horizontal(rv_recommend);
        mRecommendAdapter = new SimilarAdapter(getContext(),new ArrayList<Goods>());
        rv_recommend.setAdapter(mRecommendAdapter);
        mRecommendAdapter.listener(activity());
        recommends();

        rv_favourable.setHasFixedSize(true);
        rv_favourable.setNestedScrollingEnabled(false);
        rv_favourable.setLayoutManager(new GridLayoutManager(getContext(),2));
        mFavourableAdapter = new FavourableAdapter(getContext(),new ArrayList<Goods>());
        rv_favourable.setAdapter(mFavourableAdapter);
        mFavourableAdapter.listener(activity());
        mFavourableAdapter.setOnShoppingListener(new GoodsAdapter.OnShoppingListener() {
            @Override
            public void onAdd2Car(int number) {
                activity().updateNumber(number);
            }
        });
        //favourables();

    }

    /**广告banner*/
    private void banners(){
        EClient.with().post(EApi.INDEX_BANNER, new EObserver() {
            @Override
            public void successful(EResponse response) {

                banners = response.list("list",Banner.class);
                cb_banner.setPages(new CBViewHolderCreator() {
                    @Override
                    public Object createHolder() {
                        return new BannerHolder();
                    }
                },banners);
            }

            @Override
            public void failure(String msg) {
            }
        });
    }

    /**推荐商品*/
    private void recommends(){
        EClient.with().post(EApi.INDEX_RECOMMEND, new EObserver() {
            @Override
            public void successful(EResponse response) {
                List<Goods> list = response.list(Goods.class);
                mRecommendAdapter.refresh(list);
            }

            @Override
            public void failure(String msg) {
            }

        });
    }

    /**推荐商家*/
    private void agents(){
        Observable<EResponse> observable = EClient.with().api().agent(WApp.lngLat());
        EClient.with().observer(observable, new EObserver() {
            @Override
            public void successful(EResponse response) {
                List<Agent> list = response.list(Agent.class);
                mAgentAdapter.refresh(list);
            }

            @Override
            public void failure(String msg) {

            }
        });
    }

    /**附近商家*/
    private void nearby(){
        Observable<EResponse> observable = EClient.with().api().post(EApi.AGENT_NEARBY,WApp.lngLat());
        EClient.with().observer(observable, new EObserver() {
            @Override
            public void successful(EResponse response) {
                List<Agent> list = response.list(Agent.class);
                //将附近商家显示再地图上
                toMapMarker(list);
            }

            @Override
            public void failure(String msg) {

            }
        });

    }

    private List<Agent> mNearbyAgents = new ArrayList<>();
    private ArrayMap<String,Marker> mMarker = new ArrayMap<>();
    private void toMapMarker(List<Agent> list){
        if (mMap == null) {
            return;
        }

        mMap.clear();
        if (list == null || list.isEmpty()) {
            return;
        }

        mNearbyAgents.addAll(list);
        LatLng last = null;
        for (Agent agent:list){
            if (TextUtils.isEmpty(agent.latitude) || TextUtils.isEmpty(agent.longitude)){
                continue;
            }

            double lng = WUtils.toDouble(agent.longitude);
            double lat = WUtils.toDouble(agent.latitude);
            if (lng == 0 || lat == 0) {
                continue;
            }

            LatLng latLng = new LatLng(lat, lng);
            last = latLng;
            Marker marker = mMap.addMarker(new MarkerOptions().position(latLng).icon(BitmapDescriptorFactory.fromResource(R.drawable.map_marker_normal)));
            marker.setTag(agent);
            mMarker.put(agent.id,marker);
        }

        if (last !=null){
            mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(last, zoom));
        }

    }

    /**优惠商品*/
    private void favourables(){
        EClient.with().post(EApi.INDEX_FAVORABLE, new EObserver() {
            @Override
            public void successful(EResponse response) {
                List<Goods> list = response.list(Goods.class);
                mFavourableAdapter.refresh(list);
            }

            @Override
            public void failure(String msg) {
            }
        });

    }

    private void categories(){
        EClient.with().post(EApi.INDEX_GOODS_CATEGORY, new EObserver() {
            @Override
            public void successful(EResponse response) {
                List<GoodsCategory> list = response.list(GoodsCategory.class);
                List<GoodsCategory> categories = sublist(list);
                mGoodsCategoryAdapter.refresh(categories);
            }

            @Override
            public void failure(String msg) {

            }
        });
    }

    private List<GoodsCategory> sublist(List<GoodsCategory> list){
        if (EUtils.isEmpty(list)){
            return list;
        }

        GoodsCategory more = new GoodsCategory();
        more.more = R.drawable.ic_home_more;
        more.category_name = category_more;

        if (list.size() >7){
            List<GoodsCategory> categories = new ArrayList<>(8);
            for (int i=0;i<7;i++){
                categories.add(list.get(i));
            }
            categories.add(7,more);
            return categories;
        }
        list.add(more);
        return list;
    }

    private GLocation gLocation;
    private int zoom = 15;
    private boolean first = true;
    private void initLocation(){
        gLocation = new GLocation(activity()){
            @Override
            protected void successful(double lng, double lat) {
                super.successful(lng, lat);
                WApp.onLocationSuccessful(lng,lat);
                onLocation();
            }

            @Override
            protected void failure() {
                super.failure();

                agents();
                nearby();
            }

            @Override
            public void onLocationChanged(Location location) {
                super.onLocationChanged(location);
                if (mMap !=null && location !=null) {
                    WApp.onLocationSuccessful(location.getLongitude(),location.getLatitude());
                    LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
                    mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom));
                    onLocation();
                }
            }
        };
        gLocation.setZoom(zoom);
    }

    private void onLocation(){
        if(first) {
            Log.i(TAG,"定位成功");
            first = false;
            agents();
            nearby();
        }
    }

    private void map(Bundle savedInstanceState){
        initLocation();
        mv_map.onCreate(savedInstanceState);
        mv_map.onResume();
        try {
            MapsInitializer.initialize(getActivity());
        } catch (Exception e) {
            e.printStackTrace();
        }
        int errorCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this.getActivity());
        if (ConnectionResult.SUCCESS != errorCode) {
            GooglePlayServicesUtil.getErrorDialog(errorCode,
                    this.getActivity(), 0).show();
        } else {
            mv_map.getMapAsync(this);
            Log.i(GLocation.TAG,"getMapAsync");
        }
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        Log.i(GLocation.TAG,"onMapReady");
        this.mMap = googleMap;
        mMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
        mMap.setTrafficEnabled(true);
        mMap.getUiSettings().setZoomControlsEnabled(true);
        mMap.getUiSettings().setZoomGesturesEnabled(false);
        mMap.setOnMapClickListener(this);
        mMap.setOnMarkerClickListener(this);
        gLocation.onMapReady(mMap);
    }

    @Override
    public void onMapClick(LatLng latLng) {
        MapActivity.toMap(activity(),mNearbyAgents,"nearby");
    }

    @Override
    public boolean onMarkerClick(Marker marker) {
        for (Marker m:mMarker.values()){
            m.setIcon(BitmapDescriptorFactory.fromResource(R.drawable.map_marker_normal));
        }

        marker.setIcon(BitmapDescriptorFactory.fromResource(R.drawable.map_market_select));

        Object tag = marker.getTag();
        if(tag !=null && tag instanceof Agent) {
            Agent agent = (Agent)tag;
            AgentDetailActivity.toDetail(activity(),agent.id);
        }

        return true;
    }

    @OnClick(R.id.iv_scanner)
    protected void onScannerClick(){
        if(!BuildConfig.DEBUG) {
            activity().toActivity(ScannerActivity.class);
        }else {
            activity().toActivity(ScannerActivity.class);
            //WelcomeDialog.with(getContext()).show();
            //ShareDialog.with(getContext()).show();
            //activity().toActivity(PayActivity.class);

//            Agent agent = new Agent();
//            agent.user_id = "35";
//            agent.agent_name = "agent";
//            agent.logo = "http://i5.hexunimg.cn/2016-09-12/185985253.jpg";
//            ConsultActivity.toConsult(activity(),agent);

            //activity().toActivity(ScannerActivity.class);
//            activity().toActivity(AgentInfoActivity.class);
        }

    }

    @OnClick(R.id.tv_search)
    protected void onSearchClick(){
        activity().toActivity(SearchActivity.class);
    }

    @OnClick(R.id.ll_goods_recommend)
    protected void onGoodsRecommendClick(){
        GoodsActivity.toRecommend(activity());
    }

    @OnClick(R.id.ll_agent_recommend)
    protected void onAgentRecommendClick(){
        AgentsActivity.toRecommend(activity());
    }

    @Override
    public void onStart() {
        super.onStart();
        if (mv_map !=null) mv_map.onStart();
        if (gLocation !=null){
            gLocation.onStart();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mv_map !=null) mv_map.onResume();
        cb_banner.startTurning(5000);
        if (gLocation !=null){
            gLocation.onResume();
        }

        favourables();
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mv_map !=null) mv_map.onPause();
        if (gLocation !=null){
            gLocation.onPause();
        }

    }

    @Override
    public void onStop() {
        super.onStop();
        if (mv_map !=null) mv_map.onStop();
        cb_banner.stopTurning();
        if (gLocation !=null){
            gLocation.onStop();
        }
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        if (mv_map !=null) mv_map.onLowMemory();
    }

    @Override
    public void onDestroy() {
        if (mv_map !=null) mv_map.onDestroy();
        super.onDestroy();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        gLocation.onActivityResult(requestCode,resultCode,data);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        gLocation.onRequestPermissionsResult(requestCode,permissions,grantResults);
    }
}
